import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
@SuppressWarnings("all")
@WebServlet("/CookieDemo1")
public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        boolean found = false;
        if(cookies != null) {
            found = true;
            for(Cookie cookie : cookies) {
                String name = cookie.getName();
                if(cookie.getName().equals("lastTime")) {
                    Date date = new Date();
                    cookie.setValue(date.toString());
                    cookie.setMaxAge(60*60*24*30);
                    resp.addCookie(cookie);
                    String value = cookie.getValue();
                    resp.getWriter().write("<h1>欢迎回来,您上次登录时间为"+value+"</h1>");
                    break;
                }
            }
        }
        if(found == false || cookies==null || cookies.length == 0) {
        Date date = new Date();
            Cookie cookie = new Cookie("lastTime", date.toString());
            cookie.setMaxAge(60*60*24*30);
            resp.getWriter().write("欢迎新用户");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
